import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { Card, message, Form, Input, Modal, Checkbox, Button, Upload, Select, Radio } from 'antd';
import { FormInstance } from 'antd/lib/form';
import { UploadOutlined, FolderOpenOutlined, SaveOutlined, DownloadOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import { Graph, Model, Node, Edge, Shape } from '@antv/x6'
import JSZip from 'jszip';
import * as xmind from 'xmind';
import Hierarchy from '@antv/hierarchy';
import TreeView from '../treeView';

interface HierarchyResult {
  id: number
  faultCode: any
  x: number
  y: number
  data: {
    faultCode: string
    faultDescription: string
  }
  children: HierarchyResult[]
}
const mapStateToProps = (state: any) => ({
  knowledgeApply: state.knowledgeApply,
  // loading: state.loading.effects['http/getDataWithRes'],
});

class ApplyModal extends PureComponent<any, any> {
  constructor(props: any) {
    super(props);
    let userAccount: any = '';
    try {
      userAccount = sessionStorage.getItem('accountName');
    } catch (e) {}
    this.state = {
      userAccount: userAccount,  //  用户名
      userId: '', //  用户id
      type: '1',  //  当前树/完整树
      screenFit: '1',
      currentSpecialty: '', //  当前所选专业
      hasUpload: false, //  是否上传文件
      viewFullTreeLock: true, //  完整故障树预览按钮是否禁用
      currentData: [],  //  当前上传xmind数据（经整理）
      currentIds: {}, //  当前上传xmind数据节点关系
      currentTargetModel: [],
      sourceData: [], //  当前专业tree数据
      fullData: [], //  完整树数据
      fullIds: {},  //  完整树数据节点关系
      fullTargetModel: [],  //  
    }
  }

  componentDidMount() {
    const { dispatch, user } = this.props;
    this.props.onRef(this);
    // console.log(JSZip)
    const { userAccount } = this.state;

    dispatch({
      type: 'http/getDataWithRes',
      payload: { 
        url: '/findSidByAccountName',
        accountName: userAccount,
      },
      callback: (res: any) => {
        if (res.statusCode) {
          this.setState({
            userId: res.data || '',
          })
        }
      }
    })
  }

  componentDidUpdate(prevProps: any) {
    const { modalVisible, record } = this.props;
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      console.log(record);
      if (record.id) {
        //  编辑
        this.queryApplyRecordData({
          id: record.applyRecordId,
        }).then((res1: any) => {
          if (res1.statusCode == '0') {
            //  本次上传tree跟节点
            const tempDesp = res1?.data?.faultTree[0]?.faultDescription;
            this.queryFullTreeData({
              majorCode: record.majorCode,
              faultDescription: tempDesp,
              pageNo: 1,
              pageSize: 999
            }).then((res2: any) => {
              if (res2.statusCode == '0') {
                //  专业 + 根节点描述 --> 查找知识库
                const tempRootId = res2?.data?.list[0]?.rootId || -1;
                console.log(tempRootId);
                this.queryFullTreeData({
                  majorCode: record.majorCode,
                  rootId: tempRootId,
                  pageNo: 1,
                  pageSize: 9999,
                }).then((res3: any) => {
                  if (res3.statusCode == '0') {
                    //  当前提交数据
                    const currentTree = this.formatCurrentData(res1?.data?.faultTree || []);
                    //  关系
                    const ids = this.getFulltreeIds(currentTree);
                    //  坐标
                    const currentDataModel = this.getCoordinates(currentTree[0]);
                    const currentTargetModel = this.transformModel(currentDataModel, ids);
          
                    //  完整tree
                    const sourceData = this.formatSourceTreeData(res3?.data?.list);
                    const sourceDataList = this.treeToArray1(sourceData, '');
                    const fullData = this.combineTreeData(currentTree, sourceDataList);
                    const fullDataIds = this.getFulltreeIds(fullData);
                    //  计算坐标
                    const fullDataModel = this.getCoordinates(fullData[0]);
                    //  整理tree视图数据
                    const fullTargetModel = this.transformModel(fullDataModel, fullDataIds);
                    this.setState({
                      viewFullTreeLock: false,
                      currentData: currentTree,
                      currentIds: ids,
                      currentTargetModel: currentTargetModel,
                      sourceData: sourceDataList, //  完整tree（经整理后list）
                      fullData: fullData,
                      fullIds: fullDataIds,
                      fullTargetModel: fullTargetModel,
                      currentSpecialty: record.majorCode,
                    }, () => {
                      this.treeViewRef.setData(currentTargetModel, ids);
                    })
                  }
                })
              }
            })
          }
        })
        /* if (record.rootId) {
          Promise.all([
            dispatch({
              type: 'http/getDataWithRes',
              payload: { 
                url: '/mscontent/knowledge/apply/record/findApplyRecord',
                id: record.applyRecordId,
              },
              callback: (res: any) => {
                // 获取当前tree
              }
            }),
            dispatch({
              type: 'http/getDataWithRes',
              payload: { 
                url: '/mscontent/knowledge/fault/list',
                majorCode: record.majorCode,
                rootId: record.rootId,
                pageNo: 1,
                pageSize: 9999,
              },
              callback: (res: any) => {
                //  获取完整tree
              }
            })
          ]).then((res: any) => {
            //  当前提交数据
            const currentTree = this.formatCurrentData(res[0]?.data?.faultTree || []);
            //  关系
            const ids = this.getFulltreeIds(currentTree);
            //  坐标
            const currentDataModel = this.getCoordinates(currentTree[0]);
            const currentTargetModel = this.transformModel(currentDataModel, ids);
  
            //  完整tree
            const sourceData = this.formatSourceTreeData(res[1]?.data?.list);
            const sourceDataList = this.treeToArray1(sourceData, '');
            const fullData = this.combineTreeData(currentTree, sourceDataList);
            const fullDataIds = this.getFulltreeIds(fullData);
            //  计算坐标
            const fullDataModel = this.getCoordinates(fullData[0]);
            //  整理tree视图数据
            const fullTargetModel = this.transformModel(fullDataModel, fullDataIds);
            this.setState({
              currentData: currentTree,
              currentIds: ids,
              currentTargetModel: currentTargetModel,
              sourceData: sourceDataList, //  完整tree（经整理后list）
              fullData: fullData,
              fullIds: fullDataIds,
              fullTargetModel: fullTargetModel,
              currentSpecialty: record.majorCode,
            }, () => {
              this.treeViewRef.setData(currentTargetModel, ids);
            })
          })
        } */
      }
    }
  }

  //  获取本次提交知识库
  queryApplyRecordData = (params: {}) => {
    const { dispatch } = this.props;
    return dispatch({
      type: 'http/getDataWithRes',
      payload: { 
        url: '/mscontent/knowledge/apply/record/findApplyRecord',
        ...params,
      },
      callback: (res: any) => {
        // 获取当前tree
      }
    })
  }

  //  获取完整知识库
  queryFullTreeData = (params: {}) => {
    const { dispatch } = this.props;
    return dispatch({
      type: 'http/getDataWithRes',
      payload: { 
        url: '/mscontent/knowledge/fault/list',
        ...params,
      },
      callback: (res: any) => {
        // 获取当前tree
      }
    })
  }

  //  整理当前数据（使用 faultCode 作id）
  formatCurrentData = (list: any[]) => {
    const tempList = JSON.parse(JSON.stringify(list));
    function formatData(tree: any[]) {
      for (let item of tree) {
        const tempChildren = item?.children || [];
        // const texts = item.title.split('-');
        item.id = item.faultCode || '';
        if (tempChildren.length > 0) {
          formatData(item.children)
        }
      }
    }
    formatData(tempList);
    return tempList
  }

  //  整理完整tree数据
  formatSourceTreeData = (list: []) => {
    return this.arrayToTree1(list, 'parentId');
  }


  arrayToTree1 = (items: any, pKey: string) => {
    let res = []; // 存放结果集
    let map = {};
    // 判断对象是否有某个属性
    let getHasOwnProperty = (obj: any, property: any) => Object.prototype.hasOwnProperty.call(obj, property);
    // 边做map存储，边找对应关系
    for (const i of items) {
      map[i.id] = {
        ...i,
        title: i.faultCode + '-' + i.faultDescription,
        children: getHasOwnProperty(map, i.id)
          ? map[i.id].children
          : [],
      };
      const newItem = map[i.id];
      if (!i[pKey]) {
        // newItem[pKey] = i.faultCode;
        res.push(newItem);
      } else {
        if (!getHasOwnProperty(map, i[pKey])) {
          map[i[pKey]] = {
            children: [],
          };
        }
        map[i[pKey]].children.push(newItem);
      }
    }
    return res;
  }

  treeToArray1 = (tree: any, pcode: string) => {
    let res: any[] = [];
    for (const item of tree) {
      const {
        children,
        faultCode,
        faultDescription,
        ...i
      } = item;
      if (children && children.length > 0) {
        const temp = this.treeToArray1(children, faultCode);
        res = res.concat(temp);
      }
      res.push({
        faultCode,
        faultDescription,
        parrentCode: pcode,
        ...i
      });
    }
    return res;
  }


  //  获取树节点关系
  getFulltreeIds = (data: any[]) => {
    const ids = {};
    function formatData(tree: any[]) {
      for (let item of tree) {
        const { children } = item
        ids[item.faultCode] = [];
        if (children.length > 0) {
          ids[item.faultCode] = children.map(t => t.faultCode);
          formatData(children)
        }
      }
    }
    if (data[0]) {
      const topicChildren = data[0]?.children || [];
      ids[data[0].faultCode] = topicChildren.map(t => t.faultCode);
      topicChildren && formatData(data[0]?.children);
    }
    return ids;
  }

  //  计算坐标
  getCoordinates = (data: any) => {
    if (data) {
      const result = Hierarchy.mindmap(data, {
        direction: 'H',
        getHeight() {
          return 120
        },
        getWidth() {
          return 100
        },
        getHGap() {
          return 200
        },
        getVGap() {
          return 1
        },
        getSide: () => {
          return 'right'
        },
      })
      const model: Model.FromJSONData = { nodes: [], edges: [] };
      const traverse = (data: HierarchyResult) => {
        let tempCaseNum = data.data.caseNum ?? 0;
        if (data) {
          model.nodes?.push({
            id: `${data.data.faultCode}`,
            x: data.x + 250,  //
            y: data.y + 250,  //
            code: data.data.faultCode,
            desp: data.data.faultDescription,
            caseNum: tempCaseNum,
            // title: data.data.faultDescription,
            shape: 'circle',
            width: 260,
            height: 88,
            attrs: {
              body: {
                fill: '#5F95FF',
                stroke: 'transparent',
                rx: 10,
                ry: 10,
              },
            },
          })
        }
        if (data.children) {
          data.children.forEach((item: HierarchyResult) => {
            model.edges?.push({
              source: `${data.data.faultCode}`, //  data.id
              target: `${item.data.faultCode}`, //  data.id
              attrs: {
                line: {
                  stroke: '#A2B1C3',
                  strokeWidth: 1,
                  targetMarker: null,
                },
              },
            })
            traverse(item)
          })
        }
      }
      traverse(result);
      return model;
    } else {
      return {
        nodes: [],
        edges: [],
      }
    }    
  }

  //  合并
  combineTreeData = (currentData: any, sourceData: any[]) => {
    const tempCurrent = JSON.parse(JSON.stringify(currentData));
    const tempSource = JSON.parse(JSON.stringify(sourceData));
    let tempFullData: any[] = [];
    const res1 = this.treeToArray(tempCurrent, '');
    let res = {};
    tempSource.forEach((item: any) => {
      res[item.faultCode] = {
        ...item,
      };
    });
    res1.forEach((item) => {
      const tempData = res[item.faultCode];
      let tempCaseNum = 0;
      if (tempData) {
        tempCaseNum = tempData.caseNum ?? 0;
      }
      res[item.faultCode] = {
        ...item,
        caseNum: tempCaseNum,
      };
    });
    tempFullData = this.arrayToTree(Object.values(res));
    return tempFullData;
  }  

  //  上传xmind文件
  beforeUpload = (file: any) => {
    return false;
  }

  //  文件change
  onChange = (info: any) => {
    if (info.file) {
      this.readFileData(info.file)
    }
  }

  //  读取xmind文件数据
  readFileData = (file: any) => {
    const { record } = this.props;
    const { currentSpecialty, type } = this.state;
    const jszip = new JSZip()
    jszip.loadAsync(file).then((res: any) => {
      res.forEach((el: any, obj: any) => {
        // 区分xmind8与xmindzend
        // console.log(zip.files.hasOwnProperty("manifest.json"));
        if (el  === "content.json") {
          res.file(el).async('string').then((content: any) => {
            const data: any = JSON.parse(content);
            if (data[0]?.rootTopic) {
              const res = this.formatSourceData([data[0]?.rootTopic]);
              //  计算坐标
              const dataModel = this.getCoordinates(res?.data[0]);
              //  整理tree视图数据
              const targetModel = this.transformModel(dataModel, res.ids);
              if (currentSpecialty) {
                //  已选专业
                const tempDesp = res?.data[0]?.faultDescription;
                this.queryFullTreeData({
                  majorCode: currentSpecialty,
                  faultDescription: tempDesp,
                  pageNo: 1,
                  pageSize: 999
                }).then((res1: any) => {
                  if (res1.statusCode == '0') {
                    const tempRootId = res1?.data?.list[0]?.rootId || -1;
                    this.queryFullTreeData({
                      majorCode: currentSpecialty,
                      rootId: tempRootId,
                      pageNo: 1,
                      pageSize: 9999,
                    }).then((res2: any) => {
                      if (res2.statusCode == '0') {
                        const tempCurrentTree = res.data || [];
                        //  完整tree
                        const sourceData = this.formatSourceTreeData(res2?.data?.list);
                        const sourceDataList = this.treeToArray1(sourceData, '');
                        const fullData = this.combineTreeData(tempCurrentTree, sourceDataList);
                        const fullDataIds = this.getFulltreeIds(fullData);
                        //  计算坐标
                        const fullDataModel = this.getCoordinates(fullData[0]);
                        //  整理tree视图数据
                        const fullTargetModel = this.transformModel(fullDataModel, fullDataIds);
                        console.log(fullTargetModel);
                        this.setState({
                          sourceData: sourceDataList, //  完整tree（经整理后list）
                          fullData: fullData,
                          fullIds: fullDataIds,
                          fullTargetModel: fullTargetModel,
                          viewFullTreeLock: false,  //  解锁预览按钮
                        }, () => {
                          if (type == '2') {
                            this.treeViewRef.setData(fullTargetModel, fullDataIds);
                          }
                        })
                      }
                    })
                  }
                })
              }

              this.setState({
                currentData: res.data || [],  //  当前上传xmind数据（经整理）
                currentIds: res.ids || {}, //  当前上传xmind数据节点关系
                currentTargetModel: targetModel,
                hasUpload: true,
              }, () => {
                const { currentIds } = this.state;
                if (type == '1') {
                  this.treeViewRef.setData(targetModel, currentIds);
                }
              })
            }
          })
        }
      });
    })
  }

  //  整理数据（本地上传的xmind文件: ***使用code作id）
  formatSourceData = (list: any[]) => {
    let data = JSON.parse(JSON.stringify(list));
    const ids = {};
    function formatData(tree: any[]) {
      for (let item of tree) {
        const tempChildren = item?.children?.attached || [];
        const texts = item.title.split('-');
        item.faultCode = texts[0] || '';
        item.faultDescription = texts[1] || '';
        item.children = tempChildren;
        item.id = texts[0] || ''; //  使用 code
        ids[item.faultCode] = [];
        if (tempChildren.length > 0) {
          ids[item.faultCode] = tempChildren.map(t => {
            const texts = t.title.split('-');
            return texts[0] || ''
          });
          formatData(item.children)
        }
      }
    }
    if (data[0]) {
      const topicChildren = data[0]?.children?.attached || [];
      data[0].id = 'topic';
      data[0].faultCode = 'topic';
      data[0].faultDescription = data[0].title;
      data[0].children = topicChildren;
      ids[data[0].faultCode] = topicChildren.map(t => {
        const texts = t.title.split('-');
        return texts[0] || ''
      });
      topicChildren && formatData(data[0]?.children)
    }
    return {
      data,
      ids,
    }
  }

  //  转换数据
  transformModel = (model: any, ids: any) => {
    let data = JSON.parse(JSON.stringify(model));
    const { nodes, edges } = data;
    let targetModel: any = { nodes: [], edges: edges };
    nodes.forEach((n: any, idx: number) => {
      let tempInfo = {
        code: '',
        text: n.desp
      };
      if (idx !== 0) {
        //  起始
        tempInfo.code = n.code;
      }
      let tempN = {
        id: n.id,
        shape: 'tree-node',
        width: 260,
        height: 88,
        leaf: !(ids[n.id] && ids[n.id].length > 0),
        leafLen: ids[n.id] ? ids[n.id].length : 0,
        caseNum: n.caseNum,
        x: n.x,
        y: n.y,
        attrs: {
          code: {
            textWrap: {
              text: tempInfo.code
            }
          },
          label: {
            textWrap: {
              text: tempInfo.text
            }
          },
          case: {
            textWrap: {
              text: `案例数: ${n.caseNum}`
            }
          }
        }
      }
      targetModel.nodes.push(tempN);
    })
    return targetModel;
  }

  //  选择专业
  handleSpecialtyChange = (val: any) => {
    const { dispatch } = this.props;
    const { currentData, type, hasUpload } = this.state;

    console.log(val, hasUpload);

    this.setState({
      currentSpecialty: val
    })
    //  查询完整专业树
    if (hasUpload) {
      //  如果本地已上传文件
      console.log(currentData);
      const tempDesp = currentData[0]?.faultDescription;
      this.queryFullTreeData({
        majorCode: val,
        faultDescription: tempDesp,
        pageNo: 1,
        pageSize: 999
      }).then((res1: any) => {
        if (res1.statusCode == '0') {
          const tempRootId = res1?.data?.list[0]?.rootId || -1;
          console.log(tempRootId);
          this.queryFullTreeData({
            majorCode: val,
            rootId: tempRootId,
            pageNo: 1,
            pageSize: 9999,
          }).then((res2: any) => {
            if (res2.statusCode == '0') {
              const tempCurrentTree = currentData;
              //  完整tree
              const sourceData = this.formatSourceTreeData(res2?.data?.list);
              const sourceDataList = this.treeToArray1(sourceData, '');
              const fullData = this.combineTreeData(tempCurrentTree, sourceDataList);
              const fullDataIds = this.getFulltreeIds(fullData);
              //  计算坐标
              const fullDataModel = this.getCoordinates(fullData[0]);
              //  整理tree视图数据
              const fullTargetModel = this.transformModel(fullDataModel, fullDataIds);
              this.setState({
                sourceData: sourceDataList, //  完整tree（经整理后list）
                fullData: fullData,
                fullIds: fullDataIds,
                fullTargetModel: fullTargetModel,
                viewFullTreeLock: false,  //  解锁预览按钮
              }, () => {
                if (type == '2') {
                  this.treeViewRef.setData(fullTargetModel, fullDataIds);
                }
              })
            }
          })
        }})
    }
    /* this.setState({
      currentSpecialty: val
    }, () => {
      dispatch({
        type: 'http/getDataWithRes',
        payload: { 
          url: '/mscontent/knowledge/fault/list',
          majorCode: val,
          pageNo: 1,
          pageSize: 9999
        },
        callback: (res: any) => {
          if (res.statusCode == '0') {
            const sourceData = this.formatSourceTreeData(res?.data?.list);
            const sourceDataList = this.treeToArray1(sourceData, '');
            const fullData = this.combineTreeData(currentData, sourceDataList);
            const fullDataIds = this.getFulltreeIds(fullData);
            //  计算坐标
            const fullDataModel = this.getCoordinates(fullData[0]);
            //  整理tree视图数据
            const fullTargetModel = this.transformModel(fullDataModel, fullDataIds);
            this.setState({
              sourceData: sourceDataList, //  完整tree（经整理后list）
              fullData: fullData,
              fullIds: fullDataIds,
              fullTargetModel: fullTargetModel,
            }, () => {
              if (type == 2) {
                if (fullTargetModel.nodes && fullTargetModel.nodes.length > 0) {
                  this.treeViewRef.setData(fullTargetModel, fullDataIds);
                } else {
                  this.treeViewRef.clearGraph();
                }
              }
            })
          }
        }
      })
    }) */
  }

  //  tree 转 array
  treeToArray = (tree: any, pcode: string) => {
    let res: any[] = [];
    for (const item of tree) {
      const {
        children,
        faultCode,
        faultDescription,
        attributedTitle,
        ...i
      } = item;
      if (children && children.length > 0) {
        const temp = this.treeToArray(children, faultCode);
        res = res.concat(temp);
      }
      res.push({
        faultCode,
        faultDescription,
        parrentCode: pcode,
        ...i,
      });
    }
    return res;
  }

  //  array -> tree
  arrayToTree = (items: any) => {
    let res = []; // 存放结果集
    let map = {};
    // 判断对象是否有某个属性
    let getHasOwnProperty = (obj: any, property: any) => Object.prototype.hasOwnProperty.call(obj, property);
    // 边做map存储，边找对应关系
    for (const i of items) {
      map[i.faultCode] = {
        ...i,
        children: getHasOwnProperty(map, i.faultCode)
          ? map[i.faultCode].children
          : [],
      };
      const newItem = map[i.faultCode];
      if (i.parrentCode === "") {
        res.push(newItem);
      } else {
        if (!getHasOwnProperty(map, i.parrentCode)) {
          map[i.parrentCode] = {
            children: [],
          };
        }
        map[i.parrentCode].children.push(newItem);
      }
    }
    return res;
  }

  //  切换当前树/完整树
  onChangeType = (val: any) => {
    const { type, currentTargetModel, currentIds, fullIds, fullTargetModel } = this.state;
    if (type == val) return; 
    this.setState({
      type: val
    }, () => {
      if (val == 1) {
        if (currentTargetModel.nodes && currentTargetModel.nodes.length > 0) {
          this.treeViewRef.setData(currentTargetModel, currentIds);
        } else {
          this.treeViewRef.clearGraph();
        }
      } else if (val == 2) {
        if (fullTargetModel.nodes && fullTargetModel.nodes.length > 0) {
          this.treeViewRef.setData(fullTargetModel, fullIds);
        } else {
          this.treeViewRef.clearGraph();
        }
      }
    })
  }

  //  保存知识库树
  saveKownledgeTree = () => {
    const { dispatch, record } = this.props;
    const { currentData, currentSpecialty, userAccount, userId, hasUpload } = this.state;
    const _this = this;
    if (!hasUpload) {
      message.warning('未上传文件');
      return false;
    }
    if (!currentSpecialty) {
      message.warning('请先选择专业');
      return false;
    }
    if (!(currentData && currentData.length > 0)) {
      message.warning('未上传知识库数据');
      return false;
    }
    if (!(currentData[0].children && currentData[0].children.length > 0)) {
      message.warning('知识树未编辑节点数据');
      return false;
    }
    if (!(userAccount && userId)) {
      message.error('获取用户信息异常');
      return false;
    }
    //  本次上传数据
    const currentDataCopy = JSON.parse(JSON.stringify(currentData));
    // const tempList = this.treeToArray(currentDataCopy, '');
    // const tempFaultCodes = tempList.map(item => item.faultCode);
    //  根节点描述
    const rootNodeDesp = currentDataCopy[0].faultDescription;
    const tempFaultCodes = currentDataCopy[0].children.map(n => n.faultCode);
    this.queryFullTreeData({
      majorCode:currentSpecialty,
      faultDescription: rootNodeDesp,
      pageNo: 1,
      pageSize: 10,
    }).then((res1: any) => {
      if (res1.statusCode == '0') {
        let tempRootId = res1?.data?.list[0]?.rootId;
        if (tempRootId) {
          //  知识库已存在（根节点相同）
          this.queryFullTreeData({
            majorCode:currentSpecialty,
            // faultDescription: rootNodeDesp,
            rootId: tempRootId,
            pageNo: 1,
            pageSize: 9999,
          }).then((res2: any) => {
            if (res2.statusCode == '0') {
              const sameFaultCode: any[] = [];
              res2?.data?.list && res2?.data?.list.forEach((d: any) => {
                if (tempFaultCodes.indexOf(d.faultCode) !== -1) {
                  //  存在相同二级节点
                  sameFaultCode.push(d.faultCode);
                }
              })
              if (sameFaultCode.length > 0) {
                // res.data.list
                Modal.confirm({
                  title: '覆盖确认',
                  icon: <ExclamationCircleOutlined />,
                  content: `${sameFaultCode.join('，')}节点已存在，是否覆盖？`,
                  okText: '确认',
                  onOk() {
                    _this.submitData();
                  },
                  cancelText: '取消',
                })
              } else {
                _this.submitData();
              }
            }
          })
        } else {
          _this.submitData();
        }
      }
    })


    /* dispatch({
      type: 'http/getDataWithRes',
      payload: { 
        url: '/mscontent/knowledge/fault/list',
        majorCode:currentSpecialty,
        pageNo: 1,
        pageSize: 9999,
      },
      callback: (res: any) => {
        console.log(res);
        //  获取完整tree
        if (res.statusCode == '0') {

          let sameFaultCode: any[] = [];
          res?.data?.list && res?.data?.list.forEach((d: any) => {
            if (d.parentId !== null && tempFaultCodes.indexOf(d.faultCode) !== -1 ) {
              //  存在相同二级节点
              sameFaultCode.push(d.faultCode);
            }
          })
          if (sameFaultCode.length > 0) {
            // res.data.list
            Modal.confirm({
              title: '覆盖确认',
              icon: <ExclamationCircleOutlined />,
              content: `${sameFaultCode.join('，')}节点已存在，是否覆盖？`,
              okText: '确认',
              onOk() {
                _this.submitData();
              },
              cancelText: '取消',
            })
          } else {
            _this.submitData();
          }
        }
      }
    }) */
  }

  //  提交知识库数据
  submitData = () => {
    const { dispatch, record: { id } } = this.props;
    const { currentData, currentSpecialty, userAccount, userId, hasUpload } = this.state;
    const type = id ? 'putObjWithRes' : 'postObjWithRes';
    const url = id ? '/mscontent/knowledge/apply/record/edit' : '/mscontent/knowledge/apply/save';
    const params = id ? {
      id,
      faultTree: currentData,
    } : {
      userId,
      userAccount,
      faultTree: currentData,
      majorCode: currentSpecialty,
    }

    //  获取用户id
    dispatch({
      type: 'http/getDataWithRes',
      payload: { 
        url: '/findSidByAccountName',
        accountName: userAccount || ''
      },
      callback: (res: any) => {
        if (res.statusCode == '0') {
          dispatch({
            type: `http/${type}`,
            payload: {
              url: url,
              ...params,
            },
            callback: (res: any) => {
              if (res.statusCode == '0') {
                message.success('操作成功');
                this.cancel();
              }
            }
          })
        }
      }
    })
  }

  //  下载知识库树
  downloadKownledgeTree = () => {
    const { currentData } = this.state;
    const {Workbook, Topic, Dumper, Marker} = xmind;
    if (!(currentData && currentData.length > 0)) return;
    const topicTitle = currentData[0].faultDescription;
    const workbook = new Workbook();
    const topic = new Topic({sheet: workbook.createSheet('topic', topicTitle)});
    function loopCreate(tree: any[]) {
      for (let item of tree) {
        const { children, faultCode, faultDescription } = item;
        // const tempTitle = faultCode + '-' + faultDescription;
        if (children.length > 0) {
          let tempCid = '';
          if (!faultCode || faultCode === 'topic') {
            tempCid = faultDescription
          } else {
            tempCid = faultCode + '-' + faultDescription;
          }
          children.forEach((c: any) => {
            const { faultCode = '', faultDescription = '' } = c;
            topic
              .on(topic.cid(tempCid))
              .add({title: faultCode + '-' + faultDescription})
          })
          loopCreate(children);
        }
      }
    }
    loopCreate(currentData);
    const dumper = new Dumper({workbook});
    const files = dumper.dumping();
    const jszip = new JSZip();
    for (const file of files) {
      jszip.file(file.filename, file.value);
    }
    jszip.generateAsync({ type:'blob' }).then((content) => {
      const link = document.createElement('a');
      link.href = URL.createObjectURL(content);
      link.download = `${topicTitle}.xmind`;
      link.click();
      link.remove();
    });
  }

  //  取消操作
  cancel = () => {
    const { closeModal } = this.props;
    closeModal();
    this.setState({
      type: '1',
      screenFit: '1',
      currentSpecialty: '',
      hasUpload: false,
      viewFullTreeLock: true,
      currentData: [],
      currentIds: {},
      currentTargetModel: [],
      sourceData: [],
      fullData: [],
      fullIds: {},
      fullTargetModel: [],
    })
    this.treeViewRef && this.treeViewRef.clearGraph();
  }

  //  画笔比列
  handleGraphFit = (val: any) => {
    this.setState({
      screenFit: val,
    })
    if (this.treeViewRef) {
      const { graph } = this.treeViewRef.state;
      if (val === '1' ) {
        //  适应画布
        graph && graph.zoomToFit({ padding: 24 });
      } else if (val === '2') {
        //  100%
        graph && graph.zoomTo(1);
      }
    }
  }

  render() {
    const { modalVisible, specialtyOption, record } = this.props;
    const { type, currentSpecialty, screenFit, viewFullTreeLock } = this.state;

    return (
      <>
        <Modal
          style={{ top: 20 }}
          footer={null}
          title="知识库"
          width={1200}
          bodyStyle={{ maxHeight: '800px' }}
          visible={modalVisible}
          onCancel={this.cancel}
        >
          {/* // width="100%" */}
          <div style={{ width: '100%', marginBottom: '15px' }}>
            {record.status == '1' ? null : (
              <>
                <Upload
                  beforeUpload={this.beforeUpload}
                  onChange={this.onChange}
                  maxCount={1}
                  showUploadList={false}
                  // disabled
                >
                  <Button icon={<FolderOpenOutlined />}>打开</Button>
                </Upload>
                <Button onClick={() => this.saveKownledgeTree()} icon={<SaveOutlined />}>保存</Button>
              </>
            )}
            <Button onClick={() => this.downloadKownledgeTree()} icon={<DownloadOutlined />}>下载</Button>
            <Select
              style={{ width: 200, marginLeft: '220px' }}
              value={currentSpecialty}
              disabled={record.id}
              onChange={this.handleSpecialtyChange}
              options={specialtyOption}
            />
          </div>
          <div>
            <Radio.Group 
              onChange={({target: { value }}) => {
                this.onChangeType(value)
              }}
              value={type}
              optionType="button"
              buttonStyle="solid"
            >
              <Radio.Button value="1">本次维护内容</Radio.Button>
              { record.status != 1 ? <Radio.Button disabled={viewFullTreeLock} value="2">完整故障树预览</Radio.Button> : null }
            </Radio.Group>
          </div>
          <TreeView
            onRef={(modalRef: any) => (this.treeViewRef = modalRef)}
            clickNode={(n: any) => {}}
            styels={{
              width: '100%',
              height: '670px'
            }}
          />
          <div style={{ position: 'absolute', right: '65px', bottom: '80px', }}>
            {/* 适应画布、100% */}
            <Select
              style={{
                width: '100px',
              }}
              value={screenFit}
              placeholder="缩放比列"
              onSelect={(v: any) => {
                this.handleGraphFit(v);
              }}
              options={[
                {
                  value: '1',
                  label: '适应画布',
                },
                {
                  value: '2',
                  label: '100%',
                },
              ]}
            />
          </div>
        </Modal>
      </>
    )
  }
}
export default connect(mapStateToProps)(ApplyModal);
